/*******************************************************************************
 ** Name: module.cpp                                                             **
 ** Description:                                                              **
 **                                                                           **
 ** Open Source Initiative (OSI) Approved 2-clause BSD License                **
 **                                                                           **
 **  Copyright (c) 2009-2010 Barry "Gian" James  <bjames@munixos.net>         **
 **  All rights reserved.                                                     **
 **                                                                           **
 **  Redistribution and use in source and binary forms, with or without       **
 **  modification, are permitted provided that the following conditions are   **
 **  met:                                                                     **
 **                                                                           **
 **  * Redistributions of source code must retain the above copyright notice, **
 **    this list of conditions and the following disclaimer.                  **
 **  * Redistributions in binary form must reproduce the above copyright      **
 **    notice, this list of conditions and the following disclaimer in the    **
 **    documentation and/or other materials provided with the distribution.   **
 **                                                                           **
 **  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS      **
 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED **
 ** TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A           **
 ** PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT        **
 ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,    **
 ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED  **
 ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR    **
 ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    **
 ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING      **
 ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS        **
 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.              **
 **                                                                           **
 ******************************************************************************/
// Created on March 17, 2010, 8:21 AM
// Modified $Date: 2011-09-18 21:48:59 +0000 (Sun, 18 Sep 2011) $ by $Author: gian.james $
#define module_cpp_ID   "$Id: module.cpp 145 2011-09-18 21:48:59Z gian.james $"

extern "C" {
#include <sys/types.h>
#include <dirent.h>
#include <dlfcn.h>
}
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
using boost::property_tree::ptree;

#include "common.hpp"
#include "module.hpp"
#include "log.hpp"


///////////////////////////////[ Module

Module::Module(const std::string & n)
{
	name = n;
	desc = "";
	loaded = false;
	lib = 0;
    boost::uuids::random_generator gen;
    oid = gen();
}
//
//void
//Module::GenUUID()
//{
//	boost::uuids::random_generator gen;
//	oid = gen();
//}

///////////////////////////////[ ModuleManager

ModuleManager::ModuleManager()
{

}

ModuleManager::~ModuleManager()
{
	DBGFUNC();
	std::list<Module*>::iterator i;
	for (i = modules.begin(); i != modules.end(); i++)
	{
		Module * mod = *i;
		if (mod->Loaded()) {
			void * lib = mod->Library();
			dlclose(lib);
			delete mod;
		}
	}
}

int
ModuleManager::Init()
{
	DBGFUNC();
	int num = 0;
	DIR * dfd, *mfd;
	dirent * dp, *mp;
	ptree pt;
	Module * mod;

	dfd = opendir(DEFAULT_MODULE_DIR);
	for (int c = 0; dp = readdir(dfd); )
	{
		if (strcmp(dp->d_name,".") && strcmp(dp->d_name,".."))
		{
			std::cout << dp->d_name << std::endl;
			mfd = opendir(dp->d_name);
			for (int num = 0; mp = readdir(mfd); )	// maybe a while() ?
			{
				if (!strcmp(mp->d_name,"index.xml")) {
					read_xml(mp->d_name,pt);
					mod = new Module(pt.get<std::string>("module.name"));
					mod->Version(pt.get<std::string>("module.version"));
					mod->Author(pt.get<std::string>("module.author"));
					mod->Desc(pt.get<std::string>("module.desc"));
					mod->Entry(pt.get<std::string>("module.entry"));
					mod->InitSupplied(pt.get<bool>("module.init"));
					mod->FiniSupplied(pt.get<bool>("module.fini"));
					mod->Location(pt.get<std::string>("module.lib"));
					modules.push_back(mod);
					++num;
				}
//				std::string	buf = mp->d_name;
//				if (!buf.compare(buf.size()-3,3,".so"))
//				{
//
//				}
			}
		}
	}
	return num;
}

typedef void * (*initFunc)();

int
ModuleManager::LoadModule(const std::string & m)
{
	DBGFUNC();
	if (access(m.data(),R_OK))
		return ModError::NonExist;

	std::list<Module *>::const_iterator i;
	for (i = modules.begin(); i != modules.end(); i++) {
		if ((*i)->Name() == m && (*i)->Loaded())
			return ModError::AlreadyLoaded;
	}
	void * lib = dlopen(m.data(),RTLD_NOW|RTLD_GLOBAL);
	if (!lib) {
		debug::log->out(LOG_CRIT,"LoadModule(): %s",dlerror());
		return ModError::Unknown;
	}
	initFunc func = (initFunc)dlsym(lib,(*i)->Entry().data());
	if (func)
		(*i)->SetModule((ModuleBase*)func());
	else
		return ModError::NoEntry;

	(*i)->Library(lib);
	(*i)->Loaded(true);

	return (int)1;
}

int
ModuleManager::LoadModules()
{
	DBGFUNC();
	std::list<Module *>::iterator i;
	for (i = modules.begin(); i != modules.end(); ++i)
	{
		LoadModule((*i)->Name());
	}
	return modules.size();
}

bool
ModuleManager::UnloadModule(const std::string & m)
{
	DBGFUNC();
	std::list<Module*>::iterator i;
	for (i = modules.begin(); i != modules.end(); i++)
	{
		Module * mod = *i;
		if (mod->Loaded() && mod->Name() == m) {
			void * lib = mod->Library();
			dlclose(lib);
			delete mod;
			return true;
		}
	}
	return false;
}

void
ModuleManager::Print() const
{

}
